﻿var map, maplayer, markerlayer, clusterLayer, centerlayer, vectorLayer, geoLayer, modifyFeature, drawBounds, marker, host = "http://192.168.1.245:8090";
var url = host + "/iserver/services/map-WuZhouGisBaidu18/rest/maps/WUZhoubaidu18",
url2 = host + "/iserver/services/data-WZPoint/rest/data/datasources/devicePoint/datasets/Device",
url3 = host + "/iserver/services/data-WZPoint/rest/data",
url4 = host + "/iserver/services/data-LineData/rest/data";
var url5 = host + "/iserver/services/components-rest/rest/data/datasources/name/devicePoint/datasets/name/Device/features.rjson?_method=DELETE&deleteMode=SQL";
var SuppiNewData = "devicePoint:Device", SuppiNewDataName = "Device@devicePoint", address = "lineData:QueryResult", addressName = "QueryResult@lineData";
var isdrag = false, isflag = false; var add = 0, dis, CircularX, CircularY, addtype, cd = 1; var police = []; var devices = [];
var infowin = null; var navigation, clickfield, clickMarker, clickfeatrue, clickType, regionFeatures, mousetype = 1;
var style1 = {
    strokeColor: "#FF0000",
    strokeWidth: 1,
    pointerEvents: "visiblePainted",
    fill: false
}, circleStyle = {
    strokeColor: "#F08080",
    fillColor: "#B8860B",
    strokeWidth: 2,
    fillOpacity: 0.5
};
function init(root) {
    navigation = new SuperMap.Control.Navigation();
    map = new SuperMap.Map("map", { controls: [
            navigation
        //new SuperMap.Control.LayerSwitcher()
            ], units: "m", eventListeners: { "movestart": function () {
                $("#result").css("display", "none");
                $(".devrel").css("display", "none");

            }, "click": function () {
                $("#result").css("display", "none");
                $(".devrel").css("display", "none");
            }
            }
    });
    map.restrictedExtent = new SuperMap.Bounds(110.03, 22.4, 111.92, 24.32);
    maplayer = new SuperMap.Layer.TiledDynamicRESTLayer("梧州市", url, {
        transparent: true,
        cacheEnabled: true
    }, {
        maxResolution: "auto",
        useCanvas: false,
        useCORS: true
    });
    maplayer.events.on({ "layerInitialized": function () { addLayer(root); } });
    vectorLayer = new SuperMap.Layer.Vector("VectorLayer");
    geoLayer = new SuperMap.Layer.Vector("GeoLayer");
    markerlayer = new SuperMap.Layer.Markers("markerLayer");
    centerlayer = new SuperMap.Layer.Markers("centerLayer");
    modifyFeature = new SuperMap.Control.ModifyFeature(vectorLayer);
    //定义框选控件和几何控件
    drawBounds = new SuperMap.Control.DrawFeature(vectorLayer, SuperMap.Handler.Box);
    drawBounds.events.on({ "featureadded": drawCompleted });
    var div = document.getElementById("map");
    var events = new SuperMap.Events(div, div, ["userselect"]);
    div.events = events;
    div.events.register("userselect", div, userselectHandler);
    var observeFun = SuperMap.Function.bindAsEventListener(clickHandler, div);
    SuperMap.Event.observe(div, "click", observeFun);
    map.events.on({
        "move": move
    });
}

var range = 1;
//根据范围圈选
function circleStar(type) {
    markerStart(3);
}
//激活框选
function draw(type) {
    //先清除上次的显示结果
    clearAllFeatures();
    drawBounds.activate();
}
//根据所选范围查询结果集
function drawCompleted(drawBoundsArgs) {
    var darasetName = [SuppiNewData];
    var feature = drawBoundsArgs.feature;
    feature.style = style1;
    vectorLayer.addFeatures(feature);
    var bounds = feature.geometry.bounds;
    //vectorLayer.removeAllFeatures();
    var GetFeaturesByBoundsParameters, getFeaturesByGeometryService;
    GetFeaturesByBoundsParameters = new SuperMap.REST.GetFeaturesByBoundsParameters({
        datasetNames: darasetName,
        spatialQueryMode: SuperMap.REST.SpatialQueryMode.INTERSECT,
        bounds: bounds,
        toIndex: 1000000
    });
    getFeaturesByGeometryService = new SuperMap.REST.GetFeaturesByBoundsService(url3, {
        eventListeners: {
            "processCompleted": processBoundCompleted,
            "processFailed": processFaileds
        }
    });
    getFeaturesByGeometryService.processAsync(GetFeaturesByBoundsParameters);
}
function processFaileds(e) {
    if (e.error.errorMsg.indexOf("getFeatureByBounds") == -1) {
        layer.msg(e.error.errorMsg);
    }
}
function regionCompleted(feature) {
    var geometry = feature.geometry;
    vectorLayer.removeAllFeatures();
    var getFeaturesByGeometryParameters, getFeaturesByGeometryService;
    getFeaturesByGeometryParameters = new SuperMap.REST.GetFeaturesByGeometryParameters({
        datasetNames: [SuppiNewData],
        toIndex: -1,
        spatialQueryMode: SuperMap.REST.SpatialQueryMode.INTERSECT,
        geometry: feature.geometry
    });
    getFeaturesByGeometryService = new SuperMap.REST.GetFeaturesByGeometryService(url3, {
        eventListeners: {
            "processCompleted": processBoundCompleted,
            "processFailed": processFailed
        }
    });
    getFeaturesByGeometryService.processAsync(getFeaturesByGeometryParameters);
}

var num = 1;
//根据结果集添加标注
function processBoundCompleted(getFeaturesEventArgs) {
    drawBounds.deactivate();
    var i, len, features, fields, result = getFeaturesEventArgs.result;
    num = 1;
    if (result && result.features) {
        features = result.features;
        //console.log(features);
        var smIDs = [];
        var ps = [];
        for (i = 0, len = features.length; i < len; i++) {
            fields = features[i].attributes;
            $.ajax({
                type: "get",
                url: baseUrl + 'GetDeviceListByID&ID=' + fields.ID,
                async: false,
                success: function (result) {
                    //console.log(result);
                    var lresult = $.parseJSON(result);
                    if (lresult.code == 1) {
                        var data = eval(lresult.data);
                        if (data.length > 0) {
                            var f = new SuperMap.Feature.Vector();
                            f.geometry = new SuperMap.Geometry.Point(data[0].Longitude, data[0].Latitude);
                            f.style = {
                                pointRadius: 0,
                                graphic: true,
                                externalGraphic: geticon(data[0].DeviceType, data[0].Status),
                                graphicWidth: 20,
                                graphicHeight: 23,
                                graphicXOffset: -10,
                                graphicYOffset: -23
                            };
                            f.info = data[0];
                            ps.push(f);
                            //                            var size1 = new SuperMap.Size(20, 23);
                            //                            var offset = new SuperMap.Pixel(-(size1.w / 2), -size1.h);
                            //                            var icon = new SuperMap.Icon(geticon(data[0].DeviceType, data[0].Status), size1, offset);
                            //                            var marker = new SuperMap.Marker(new SuperMap.LonLat(data[0].Longitude, data[0].Latitude), icon);
                            //                            marker.events.register("mouseover", marker, function (field) {
                            //                                return function (evt) {
                            //                                    getFeatureBySQL(field.ID);
                            //                                    setTimeout(function (e) {
                            //                                        clickfield = field;
                            //                                        clickMarker = marker;
                            //                                        clickMarker.lonlat = marker.lonlat;
                            //                                        clickType = type;
                            //                                        closeInfoWin();
                            //                                        var contentHTML = "<div style='width:250px;height:260px; font-size:12px;font-weight:bold ; color:#000'>";
                            //                                        contentHTML += "<div class='datadiv' id='Title'>";
                            //                                        contentHTML += "<span id='use'>基本信息</span>";
                            //                                        contentHTML += "<div></div>";
                            //                                        contentHTML += "</div>";
                            //                                        contentHTML += "<div style='width:100%;line-height:30px;margin-bottom:10px'><div class='datadiv'><span class='Popup'>设备名称：</span>" + data[0].DeviceName + "</div>";
                            //                                        contentHTML += "<div class='datadiv'><span class='Popup'>设备类型：</span>" + field.DeviceType + "</div>";
                            //                                        contentHTML += "<div class='datadiv'><span class='Popup'>摄像头编号：</span>" + field.CameraID + "</div>";
                            //                                        contentHTML += "<div class='datadiv'><span class='Popup'>摄像头状态：</span>" + field.Status + "</div>";
                            //                                        contentHTML += "<div class='datadiv'><span class='Popup'>所属区域：</span>" + field.RegionName + "</div>";
                            //                                        contentHTML += "<div class='datadiv'><span class='Popup'>所属单位：</span>" + field.CompanyName + "</div>";
                            //                                        contentHTML += "</div>";
                            //                                        contentHTML += "<div class='datadiv gisbtndiv'>";
                            //                                        contentHTML += "<a hidefocus='false' href='javascript:void(0)' style='color:#05A9FF' onclick='javascript:EditMarker()'><img src='../img/update.png' id='img4' style='width:20px;height:20px; border:none;' />编辑</a>"; ;
                            //                                        contentHTML += "<a hidefocus='false' href='javascript:void(0)' style='color:#EC625F' onclick='javascript:deleteSelectedFeature(\"" + field.ID + "\")'><img src='../img/delete.png' id='img3' style='width:20px;height:20px; border:none;'>删除</a>";
                            //                                        //		contentHTML +="<a hidefocus='false' href='javascript:void(0)'><img src='img/声音1.png' id='img5' onmouseover='onlo(this)' onmouseout='onloi(this)' title='打开声音' style='width:20px;height:20px; border:none;' onclick='OpenEventVideo()'></a>";
                            //                                        contentHTML += "</div>";
                            //                                        contentHTML += "</div>";
                            //                                        var x = field.Longitude;
                            //                                        var y = field.Latitude;
                            //                                        //openPop(new SuperMap.LonLat(x, y),contentHTML);
                            //                                        var pixel = map.getPixelFromLonLat(new SuperMap.LonLat(x, y));
                            //                                        var popup = new SuperMap.Popup.FramedCloud("chicken",
                            //		                                    new SuperMap.LonLat(x, y),
                            //		                                    null,
                            //		                                    contentHTML,
                            //		                                    null,
                            //		                                    true);
                            //                                        infowin = popup;
                            //                                        map.addPopup(popup);

                            //                                    }, 200);
                            //                                    //layer.msg(field.CameraID)
                            //                                }
                            //                            } (data[0]));
                            //                            marker.events.register("dblclick", marker, function (field) {
                            //                                return function (evt) {
                            //                                    $("#video").css("display", "block");
                            //                                    OpenVideo(field.CameraID, field.sysid);
                            //                                    //layer.msg(field.CameraID)
                            //                                }
                            //                            } (data[0]));
                            //                            markerlayer.addMarker(marker);
                            //                            devices.push(marker);
                        }
                        
                    } else {
                        layer.msg(lresult.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatuss, errorThrown) {
                    document.write(XMLHttpRequest.responseText);
                },
                beforeSend: function (xmlHttp) {
                    xmlHttp.setRequestHeader("If-Modified-Since", "0");
                    xmlHttp.setRequestHeader("Cache-Control", "no-cache");
                }
            });
        }
        clusterLayer.addFeatures(ps);
    }
}
function activateAddFeature() {
    //先清除上次的显示结果
    vectorLayer.removeAllFeatures();
    clearAllFeatures();
}

//移除整个图层要素
function clearAllFeatures() {
    //先清除上次的显示结果
    clusterLayer.removeAllFeatures();
    vectorLayer.removeAllFeatures();
    markerlayer.clearMarkers();
    if (map.popups.length != 0) {
        var i = 0, lengthPopup = map.popups.length;
        while (i < lengthPopup) {
            map.removePopup(map.popups[0]);
            i++;
        }
    }
    $("#dragButton").css("display", "none");
    drawBounds.deactivate();
}
function closeControl() {
    navigation.deactivate();
}
function openControl() {
    navigation.activate();
}
function clickHandler(event) {
    //this对象指向绑定的object，即DIV本身
    this.events.triggerEvent("userselect", event);
}

function addLayer(root) {
    clusterLayer = new SuperMap.Layer.ClusterLayer("Cluster");

    map.addLayers([maplayer, centerlayer, vectorLayer, geoLayer, clusterLayer, markerlayer]);
    //显示地图范围
    map.setCenter(new SuperMap.LonLat(111.27329, 23.34283), 5);
    //创建聚散选择控件。该控件实现了聚散图层的鼠标事件。
    var select = new SuperMap.Control.SelectCluster(clusterLayer, {
        callbacks: {
            over: function (f) { //点击兴趣点弹出信息窗口
                closeInfoWin();
                //console.log(f.info);
                if (!f.isCluster) { //当点击聚散点的时候不弹出信息窗口
                    openInfoWin(f, root);
                }
            },
            out: function () { //点击空白处关闭信息窗口
                //closeInfoWin();
            },
            //            clickout: function () { //点击空白处关闭信息窗口
            //                closeInfoWin();
            //            },
            dblclick: function (f) {
                if (f.info != undefined) {
                    $("#video").css("display", "block");
                    console.log(f.info);
                    OpenVideo(f.info.CameraID, f.info.sysid);
                }
                //右击击事件
            }
        }
    });
    var zoom = new SuperMap.Control.Zoom();
    map.addControl(zoom);
    map.addControl(select);
    map.addControl(modifyFeature);
    map.addControl(drawBounds);
    clusterLayer.events.on({ "moveend": function (e) {//注册moveend事件，当缩放的时候关闭信息窗口
        if (e && e.zoomChanged) closeInfoWin();
    }
    });
    //激活控件。
    select.activate();
}
//显示区域
function setRegion(i) {
    var point = new SuperMap.Geometry.Point(111.25564, 23.67018);
    geoLayer.removeFeatures(regionFeatures);
    //geoLayer.removeAllFeatures();
    //创建一个GeoJSON解析器
    var geojsonParse = new SuperMap.Format.GeoJSON();
    //将GeoJSON对象转化成要素数组
    var features = geojsonParse.read(wzGenoJson);
    //最后将要素数组加到矢量图层里面进行渲染
    if (i != undefined && i != null) {

        features[i].style = {
            strokeColor: "#0D8FE5",
            fillColor: "#B8860B",
            strokeWidth: 1,
            strokeOpacity: 1,
            pointerEvents: "visiblePainted",
            label: features[i].data.name,
            fontSize: 20,
            fontColor: "#0D8FE5",
            fillOpacity: 0.3
        };
        geoLayer.addFeatures(features[i]);
        regionFeatures = features[i];
        map.setCenter(new SuperMap.LonLat(features[i].data.center[0], features[i].data.center[1]), 2);
        //map.zoomToExtent(features[i].geometry.bounds);
    } else {
        for (var i = 0; i < features.length; i++) {
            features[i].style = {
                strokeColor: "#0D8FE5",
                fillColor: "#B8860B",
                strokeWidth: 1,
                strokeOpacity: 1,
                //pointerEvents: "visiblePainted",
                label: features[i].data.name,
                fontSize: 20,
                fontColor: "#0D8FE5",
                fillOpacity: 0.1
            };
            var isd = features[i].geometry.intersects(point);
            if (isd) {
                console.log(features[i].data.name);
            }
        }
        geoLayer.addFeatures(features);
    }
    //regionCompleted(features[0]);
}

//改变标注状态
function markerStart(type) {
    if (add == 0) {
        add = 1;
    } else {
        add = 0;
    }
    addtype = type;

}
//响应自定义事件处理，点击标绘之后
function userselectHandler(event) {

    var lonlat;
    if (event.xy) {
        lonlat = map.getLonLatFromPixel(new SuperMap.Pixel(event.xy.x, event.xy.y));
    } else { //如果是
        lonlat = map.getLonLatFromPixel(new SuperMap.Pixel(event.clientX, event.clientY - 50));
    }
    var x = lonlat.lon.toFixed(5);
    var y = lonlat.lat.toFixed(5);
    if (add == 1) {
        addMarker(x, y);
        add = 0;
    }
}

//定义addMarker函数
function addMarker(x, y) {
    if (addtype == 1) {
        var size = new SuperMap.Size(44, 33);
        var offset = new SuperMap.Pixel(-(size.w / 2), -size.h);
        var icon = new SuperMap.Icon('../js/map/theme/images/marker.png', size, offset);
        //初始化标记覆盖物类
        var marker = new SuperMap.Marker(new SuperMap.LonLat(x, y), icon);
        marker.sm_capital = cd;
        //注册 click 事件,触发 mouseClickHandler()方法

        marker.events.on({
            "click": mouseClickHandler,
            "touchstart": mouseClickHandler,
            "scope": marker
        });
        //注册事件
        marker.events.register("mousedown", marker, function (e) {
            isdrag = true;
            mousetype = 1;
            //得到marker的经纬度坐标
            var lon = marker.lonlat;
            //将经纬度坐标转换成屏幕坐标
            var pixel = map.getPixelFromLonLat(lon);
            //取整
            tx = parseInt(pixel.x);
            ty = parseInt(pixel.y);
            //获取marker相对鼠标的位置
            x1 = marker ? e.clientX : event.clientX;
            y1 = marker ? e.clientY : event.clientY;
        });
        //添加覆盖物到标记图层
        markerlayer.addMarker(marker);
        devices.push(marker);
        cd++;
    }
    if (addtype == 2) {
        drawBounds.deactivate();
        var MiddlePoint = new SuperMap.Geometry.Point(x, y);
        distansGemoter = MiddlePoint;
        QueryByDistance();
    }
    if (addtype == 3) {
        creatMarker(x, y);
    }
}
//定义mouseClickHandler函数，触发click事件会调用此函数
function mouseClickHandler(event) {
    //	        $("#txtPlace").blur();
    closeInfoWin();
    var marker = this;
    var lonlat = marker.getLonLat();
    var size2 = new SuperMap.Size(0, 11);
    var offset = new SuperMap.Pixel(11, -30);
    var icon = new SuperMap.Icon("../js/map/theme/images/flash.gif", size2, offset);
    $("#Device1").find("input").val("");
    $("#cameraName").attr("data", "");
    $("#longitude").val(lonlat.lon);
    $("#latitude").val(lonlat.lat);
    layer.open({
        type: 1
		, title: "添加设备" //不显示标题栏
		, area: '300px;'
		, shade: 0.5
		, id: 'LAY_layuipro' //设定一个id，防止重复弹出
		, btn: ['保存', '取消']
		, btnAlign: 'c'
		, moveType: 1 //拖拽模式，0或者1
		, content: $("#Device1")
		, yes: function (layero) {
		    addFeatureCompleted(lonlat.lon, lonlat.lat);
		    $(".devrel").css("display", "none");
		}, end: function () {
		    $(".devrel").css("display", "none");
        }
    });
    $("#deviceName").focus();
    $(".layui-layer-shade").on("click", function () {
        $(".devrel").css("display", "none");
    })
}

//关闭报警
function closePolice() {
    for (var i = 0; i < police.length; i++) {
        markerlayer.removeMarker(police[i]);
    }
    police = [];
}
//清除设备显示
function clearDevice() {
    clusterLayer.removeAllFeatures();
    centerlayer.clearMarkers();
    markerlayer.clearMarkers();
    //    for (var i = 0; i < devices.length; i++) {
    //        markerlayer.removeMarker(devices[i]);
    //    }
    devices = [];
    //先清除上次的显示结果
    vectorLayer.removeAllFeatures();
    geoLayer.removeFeatures(regionFeatures);
    //geoLayer.removeAllFeatures();
    if (map.popups.length != 0) {
        var i = 0, lengthPopup = map.popups.length;
        while (i < lengthPopup) {
            map.removePopup(map.popups[0]);
            i++;
        }
    }
    $("#dragButton").css("display", "none");
    drawBounds.deactivate();
    modifyFeature.deactivate();

}
//添加数据 报警
function caution(x, y, videoid, sysid) {
    //alert(1);
    //markerlayer.clearMarkers();
    var size = new SuperMap.Size(44, 44);
    var offset = new SuperMap.Pixel(-(size.w / 2), -size.h);
    var icon = new SuperMap.Icon('../img/011.gif', size, offset);
    marker = new SuperMap.Marker(new SuperMap.LonLat(x, y), icon);
    markerlayer.addMarker(marker);
    police.push(marker);
    setTimeout(function () { map.setCenter(new SuperMap.LonLat(x, y), 6); }, 500);
    $("#video").css("display", "block");
    OpenVideo(videoid, sysid);
}
//显示设备
function showAlldevice(type) {
    showtool('typeBox');
    clearDevice();
    $.ajax({
        type: "get",
        url: baseUrl + 'GetDeviceListByWhere&Type=' + type,
        async: false,
        success: function (result) {
            var lresult = $.parseJSON(result);
            if (lresult.code == 1) {
                var data = eval(lresult.data);
                //timeShowDevice(data, 0)
                var ps = [];
                for (var i = 0; i < data.length; i++) {
                    var f = new SuperMap.Feature.Vector();
                    f.geometry = new SuperMap.Geometry.Point(data[i].Longitude, data[i].Latitude);
                    f.style = {
                        pointRadius: 0,
                        graphic: true,
                        externalGraphic: geticon(data[i].DeviceType, data[i].Status),
                        graphicWidth: 20,
                        graphicHeight: 23,
                        graphicXOffset: -10,
                        graphicYOffset: -23
                    };
                    f.info = data[i];
                    ps.push(f);
                    //                    showDevice(data[i]);
                    //                    if (i == data.length - 1) {
                    //                        map.setCenter(new SuperMap.LonLat(data[i].Longitude, data[i].Latitude), 5);
                    //                    }
                    //                    var geometry = new SuperMap.Geometry.Point(data[i].Longitude, data[i].Latitude);
                    //                    feau = {
                    //                        fieldNames: ["ID", "DeviceName", "CameraID", "DeviceType", "Longitude", "Latitude", "RegionName", "Company", "bak1", "bak2"],
                    //                        fieldValues: [data[i].ID, data[i].DeviceName, data[i].CameraID, data[i].DeviceType, data[i].Longitude, data[i].Latitude, "", "", data[i].bak, ""],
                    //                        geometry: geometry
                    //                    };
                    //                    SetParasql(feau);
                }
                clusterLayer.addFeatures(ps);
            } else {
                layer.msg(lresult.msg);
            }
        },
        error: function (XMLHttpRequest, textStatuss, errorThrown) {
            document.write(XMLHttpRequest.responseText);
        },
        beforeSend: function (xmlHttp) {
            xmlHttp.setRequestHeader("If-Modified-Since", "0");
            xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        }
    });
}
function timeShowDevice(data, i) {
    if (i < data.length) {
        showDevice(data[i]);
        setTimeout(function () { timeShowDevice(data, i + 1); }, 10);
        if (i == data.length - 1) {
            map.setCenter(new SuperMap.LonLat(data[i].Longitude, data[i].Latitude), 5);
        }
    }
}
function seachData() {
    var type = $("#type").text();
    var name = $("#name").val();
    if (name.trim() != "") {
        if (type.trim().indexOf("设备") != -1) {
            $.ajax({
                type: "get",
                url: baseUrl + 'GetDeviceListByWhere&Name=' + encodeURI(name),
                async: false,
                success: function (result) {
                    console.log(result);
                    var lresult = $.parseJSON(result);
                    if (lresult.code == 1) {
                        $("#result").html("");
                        var data = eval(lresult.data);
                        for (var i = 0; i < data.length; i++) {
                            var color = "#48BE45";
                            if (data[i].Status == "不在线") {
                                color = "#F75E5E";
                            }
                            var html = '<div class="rel_row" onclick=\'locationDevice(' + JSON.stringify(data[i]) + ')\'><div class="rel_row_head"><i>' + (i + 1) + '</i>' + data[i].DeviceName + '<div class="fr" style="color:' + color + '">' + data[i].Status + '</div></div>' +
                            '<div class="rel_row_body">设备类型：' + data[i].DeviceType + '<div class="fr">所属区域：' + data[i].RegionName + '</div></div></div>'
                            $("#result").append(html);
                            //showDevice(data[i]);
                        }
                        $("#result").css("display", "block");
                    } else {
                        layer.msg(lresult.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatuss, errorThrown) {
                    document.write(XMLHttpRequest.responseText);
                },
                beforeSend: function (xmlHttp) {
                    xmlHttp.setRequestHeader("If-Modified-Since", "0");
                    xmlHttp.setRequestHeader("Cache-Control", "no-cache");
                }
            });
        } else {
            var getFeatureParam, getFeatureBySQLParams, getFeatureBySQLService;
            getFeatureParam = new SuperMap.REST.FilterParameter({
                name: addressName,
                attributeFilter: " NAME like '%" + name + "%' "//and VIDEOID not in ("+devids+")
            });
            getFeatureBySQLParams = new SuperMap.REST.GetFeaturesBySQLParameters({
                queryParameter: getFeatureParam,
                datasetNames: [address],
                maxFeatures: 5000,
                fromIndex: 0,
                toIndex: 5000
            });
            //debugger;
            getFeatureBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url4, {
                eventListeners: {
                    "processCompleted": function (e) {
                        processFeatureSQLCompleted2(e);
                    },
                    "processFailed": processFailed
                }
            });
            getFeatureBySQLService.processAsync(getFeatureBySQLParams);
        }
    }
}
function processFeatureSQLCompleted2(getFeaturesEventArgs) {
    $("#result").html("");
    var i, len, features, fields, result = getFeaturesEventArgs.result;
    if (result && result.features) {
        features = result.features;
        for (i = 0, len = features.length; i < len; i++) {
            var html = '<div class="rel_row" onclick=\'locationAddress("' + features[i].data.NAME + '","' + features[i].data.SMX + '","' + features[i].data.SMY + '")\'><div class="rel_row_head"><i>' + (i + 1) + '</i>' + features[i].data.NAME + '<div class="fr"></div></div></div>'
            $("#result").append(html);
        }
        $("#result").css("display", "block");
    }
}
function locationDevice(data) {
    $("#result").css("display", "none");
    var result = eval(data);
    $("#name").val(result.DeviceName);
    map.setCenter(new SuperMap.LonLat(result.Longitude, result.Latitude), 5);
    console.log(result.Longitude, result.Latitude);
    clearDevice();
    showDevice(result);
}
function locationAddress(name, x, y) {
    console.log(x, y);
    x = parseFloat(x) - 0.000063;
    y = parseFloat(y) - 0.000232;
    $("#result").css("display", "none");
    $("#name").val(name);
    console.log(map);
    if (map != undefined) {
        map.setCenter(new SuperMap.LonLat(x, y), 5);
        var size1 = new SuperMap.Size(40, 32);
        var offset = new SuperMap.Pixel(-(size1.w / 2), -size1.h);
        var icon = new SuperMap.Icon("../js/map/theme/images/marker.png", size1, offset);
        var marker = new SuperMap.Marker(new SuperMap.LonLat(x, y), icon);
        marker.events.register("click", marker, function (name, x, y) {
            return function (evt) {
                closeInfoWin();
                var popup = new SuperMap.Popup.FramedCloud("chicken",
		            new SuperMap.LonLat(x, y),
		            null,
		            "<div style='line-height:25px;min-width:200px'>" + name + "</div>",
		            null,
		            true);
                infowin = popup;
                map.addPopup(popup);
            }
        } (name, x, y));
        markerlayer.addMarker(marker);
        devices.push(marker);
        //var pixel = map.getPixelFromLonLat(new SuperMap.LonLat(x, y));
        closeInfoWin();
        var popup = new SuperMap.Popup.FramedCloud("chicken",
		            new SuperMap.LonLat(x, y),
		            null,
		            "<div style='line-height:25px;min-width:200px'>" + name + "</div>",
		            null,
		            true);
        infowin = popup;
        map.addPopup(popup);
    } else {
        $("#name").val(name);
        $("#lon").val(x);
        $("#lat").val(y);
    }
}
function openInfoWin(feature,root) {
    var field = feature.info;
    getFeatureBySQL(feature.info.ID);
    clickfield = feature.info;
    var contentHTML = "<div style='font-size:12px;font-weight:bold ; color:#000'>";
    contentHTML += "<div class='datadiv gisbtndiv' id='Title'>";
    contentHTML += "<span id='use'>基本信息</span>";
    if (root==true) {
        contentHTML += "<a hidefocus='false' href='javascript:void(0)' style='color:#05A9FF' onclick='javascript:EditMarker()'><img src='../img/update.png' id='img4' style='width:20px;height:20px; border:none;' />编辑</a>"; ;
        contentHTML += "<a hidefocus='false' href='javascript:void(0)' style='color:#EC625F' onclick='javascript:deleteSelectedFeature(\"" + field.ID + "\")'><img src='../img/delete.png' id='img3' style='width:20px;height:20px; border:none;'>删除</a>";
    }
    contentHTML += "<div></div>";
    contentHTML += "</div>";
    contentHTML += "<div style='width:100%;line-height:30px;margin-bottom:10px'><div class='datadiv'><span class='Popup'>设备名称：</span><span class='Popup'>" + field.DeviceName + "</span></div>";
    contentHTML += "<div class='datadiv'><span class='Popup'>设备类型：</span><span class='Popup'>" + field.DeviceType + "</span></div>";
    contentHTML += "<div class='datadiv'><span class='Popup'>摄像头编号：</span><span class='Popup'>" + field.CameraID + "</span></div>";
    contentHTML += "<div class='datadiv'><span class='Popup'>摄像头状态：</span><span class='Popup'>" + field.Status + "</span></div>";
    //contentHTML += "<div class='datadiv'><span class='Popup'>所属区域：</span><span class='Popup'>" + field.RegionName + "</span></div>";
    contentHTML += "<div class='datadiv'><span class='Popup'>所属单位：</span><span class='Popup'>" + field.CompanyName + "</span></div>";
    contentHTML += "<div class='datadiv'><span class='Popup'>经度：</span><span class='Popup'>" + field.Longitude + "</span></div>";
    contentHTML += "<div class='datadiv'><span class='Popup'>纬度：</span><span class='Popup'>" + field.Latitude + "</span></div>";
    contentHTML += "</div>";
    contentHTML += "</div>";
    var x = field.Longitude;
    var y = field.Latitude;
    var popup = new SuperMap.Popup("popwin",
		new SuperMap.LonLat(x, y),
		new SuperMap.Size(300, 290),
		contentHTML,
		null,
		true
	);
    feature.popup = popup;
    infowin = popup;
    map.addPopup(popup);
    var size1 = new SuperMap.Size(20, 23);
    var offset = new SuperMap.Pixel(-(size1.w / 2), -size1.h);
    var icon = new SuperMap.Icon(geticon(field.DeviceType, field.Status), size1, offset);
    var marker = new SuperMap.Marker(new SuperMap.LonLat(field.Longitude, field.Latitude), icon);
    marker.events.register("mouseover", marker, function (field, contentHTML) {
        return function (evt) {
            setTimeout(function (e) {
                clickfield = field;
                clickMarker = marker;
                clickMarker.lonlat = marker.lonlat;
                clickType = type;
                closeInfoWin();
                var x = field.Longitude;
                var y = field.Latitude;
                //openPop(new SuperMap.LonLat(x, y),contentHTML);
                var pixel = map.getPixelFromLonLat(new SuperMap.LonLat(x, y));
                var popup = new SuperMap.Popup("popwin",
		            new SuperMap.LonLat(x, y),
		            new SuperMap.Size(300, 250),
		            contentHTML,
		            null,
		            true
	            );
                infowin = popup;
                map.addPopup(popup);
            }, 200);
            //layer.msg(field.CameraID)
        }
    } (field, contentHTML));
    marker.events.register("dblclick", marker, function (field) {
        return function (evt) {
            $("#video").css("display", "block");
            OpenVideo(field.CameraID, field.sysid);
        }
    } (field));
    clickMarker = marker;
    clickMarker.lonlat = marker.lonlat;
}
function geticon(type, statu) {
    var icon = "";
    if (type == "枪机") {
        icon = "../js/map/theme/images/device1.png";
        if (statu != "在线") {
            icon = "../js/map/theme/images/device1_out.png";
        }
    } else if (type == "球机") {
        icon = "../js/map/theme/images/device2.png";
        if (statu != "在线") {
            icon = "../js/map/theme/images/device2_out.png";
        }
    } else {
        icon = "../js/map/theme/images/device3.png";
        if (statu != "在线") {
            icon = "../js/map/theme/images/device3_out.png";
        }
    }
    return icon;
}
//显示单个设备
function showDevice(data) {
    var size1 = new SuperMap.Size(20, 23);
    var offset = new SuperMap.Pixel(-(size1.w / 2), -size1.h);
    var icon = new SuperMap.Icon(geticon(data.DeviceType, data.Status), size1, offset);
    var marker = new SuperMap.Marker(new SuperMap.LonLat(data.Longitude, data.Latitude), icon);
    marker.events.register("mouseover", marker, function (field) {
        return function (evt) {
            getFeatureBySQL(field.ID);
            setTimeout(function (e) {
                clickfield = field;
                clickMarker = marker;
                clickMarker.lonlat = marker.lonlat;
                clickType = type;
                closeInfoWin();
                var contentHTML = "<div style='font-size:12px;font-weight:bold ; color:#000'>";
                contentHTML += "<div class='datadiv gisbtndiv' id='Title'>";
                contentHTML += "<span id='use'>基本信息</span>";
                contentHTML += "<a hidefocus='false' href='javascript:void(0)' style='color:#05A9FF' onclick='javascript:EditMarker()'><img src='../img/update.png' id='img4' style='width:20px;height:20px; border:none;' />编辑</a>"; ;
                contentHTML += "<a hidefocus='false' href='javascript:void(0)' style='color:#EC625F' onclick='javascript:deleteSelectedFeature(\"" + field.ID + "\")'><img src='../img/delete.png' id='img3' style='width:20px;height:20px; border:none;'>删除</a>";
                contentHTML += "<div></div>";
                contentHTML += "</div>";
                contentHTML += "<div style='width:100%;line-height:30px;margin-bottom:10px'><div class='datadiv'><span class='Popup'>设备名称：</span><span class='Popup'>" + field.DeviceName + "</span></div>";
                contentHTML += "<div class='datadiv'><span class='Popup'>设备类型：</span><span class='Popup'>" + field.DeviceType + "</div></span>";
                contentHTML += "<div class='datadiv'><span class='Popup'>摄像头编号：</span><span class='Popup'>" + field.CameraID + "</div></span>";
                contentHTML += "<div class='datadiv'><span class='Popup'>摄像头状态：</span><span class='Popup'>" + field.Status + "</div></span>";
                //contentHTML += "<div class='datadiv'><span class='Popup'>所属区域：</span><span class='Popup'>" + field.RegionName + "</div></span>";
                contentHTML += "<div class='datadiv'><span class='Popup'>所属单位：</span><span class='Popup'>" + field.CompanyName + "</div></span>";
                contentHTML += "<div class='datadiv'><span class='Popup'>经度：</span><span class='Popup'>" + field.Longitude + "</span></div>";
                contentHTML += "<div class='datadiv'><span class='Popup'>纬度：</span><span class='Popup'>" + field.Latitude + "</span></div>";
                contentHTML += "</div>";
                contentHTML += "</div>";
                var x = field.Longitude;
                var y = field.Latitude;
                //openPop(new SuperMap.LonLat(x, y),contentHTML);
                var pixel = map.getPixelFromLonLat(new SuperMap.LonLat(x, y));

                var popup = new SuperMap.Popup("popwin",
		            new SuperMap.LonLat(x, y),
		            new SuperMap.Size(350, 290),
		            contentHTML,
		            null,
		            true
	            );
                infowin = popup;
                map.addPopup(popup);
            }, 200);
            //layer.msg(field.CameraID)
        }
    } (data));
    marker.events.register("dblclick", marker, function (field) {
        return function (evt) {
            //            markerlayer.removeMarker(this);
            //            var newmarker = this;

            //            newmarker.icon.url = "../js/map/theme/images/cluster4.png";
            //            markerlayer.removeMarker(this);
            //            markerlayer.addMarker(newmarker);
            //            console.log(this);
            //            console.log(newmarker);
            $("#video").css("display", "block");
            OpenVideo(field.CameraID, field.sysid);
            //layer.msg(field.CameraID)
        }
    } (data));
    markerlayer.addMarker(marker);
    devices.push(marker);
}
//弹出修改框
function EditMarker() {
    modifyFeature.activate();
    closeInfoWin();

    var marker = clickMarker;
    markerlayer.addMarker(marker);
    devices.push(marker);
    var lonlat = marker.lonlat;
    console.log(lonlat);
    var size2 = new SuperMap.Size(0, 11);
    var offset = new SuperMap.Pixel(11, -10);
    var icon = new SuperMap.Icon("map/theme/images/cluster1.png", size2, offset);
    var html = '<div style="font-size:12px;font-weight:bold ;width:280px;height:260px"><div class="datadiv" id="Title"><span id="use">编辑信息</span></div><div class="setMarkerDiv"><input type="hidden" id="ID" value="' + clickfield.ID + '" />' +
		'<div class="inputTitle">经度：</div><div class="inputTxt"><input type="text" id="SmX" value=' + clickfield.Longitude + ' disabled="true" /></div>' +
		'<div class="inputTitle">纬度：</div><div class="inputTxt"><input type="text" id="SmY" value=' + clickfield.Latitude + ' disabled="true" /></div>' +
		'<div class="inputTitle">设备名称：</div><div class="inputTxt"><input type="text" id="DeviceName" autocomplete="off"/></div>' +
		'<div class="inputTitle">设备类型：</div><div class="inputTxt"><input type="text" id="channel"/></div>' +
		'<div class="inputTitle">摄像机ID：</div><div class="inputTxt"><input type="text" value="' + clickfield.CameraID + '" data="' + clickfield.CameraID + '" style="width:119px" id="CameraID"/><div class="seachicon" onclick="showSeach(\'CameraID\')"><i class="icon-tool1"></i></div></div>' +
		'<div class="inputTitle" style="margin-left: 40px;margin-right: -40px;"><input class="mapBtn" type="button" onclick="javascript:moveMarker()" value="移动" /></div><div class="inputTxt" style="text-align:right"><input type="button" class="mapBtn" onclick="javascript:editFeatureCompleted(' + lonlat.lon + ',' + lonlat.lat + ')" value="确认" /></div>' +
		'</div></div>';
    //openPop(new SuperMap.LonLat(lonlat.lon, lonlat.lat),html);
    var popup = new SuperMap.Popup.Anchored("popwin",
		new SuperMap.LonLat(lonlat.lon, lonlat.lat),
		new SuperMap.Size(290, 270),
		html,
		icon,
		true, null);
    infowin = popup;
    map.addPopup(popup);
    //    $("#CameraID").combobox({
    //	    url: baseUrl + "GetVideoList", width: "165", height: "25", valueField: 'ID', textField: 'NAME',
    //	    method: "post"
    //	})
    //	$("#CameraID").combobox("setValue", clickfield.CameraID);
    $("#channel").combobox({
        width: "165", height: "25", valueField: 'value', textField: 'label',
        data: [{ value: "枪机", label: "枪机" }, { value: "球机", label: "球机" }, { value: "半球", label: "半球"}]
    })
    $("#channel").combobox("setValue", clickfield.DeviceType);
    $("#DeviceName").val(clickfield.DeviceName);
    $(".smFramedCloudPopupContent").css("z-index", "9999999");
    $(".smPopupCloseBox").on("click", function () {
        $(".devrel").css("display", "none");
    })
}
//标注绑定鼠标按下事件
function moveMarker() {
    if (clickMarker != null) {
        clickMarker.events.register("mousedown", clickMarker, function (e) {
            isdrag = true;
            mousetype = 2;
            //得到marker的经纬度坐标
            var lon = clickMarker.lonlat;
            //将经纬度坐标转换成屏幕坐标
            var pixel = map.getPixelFromLonLat(lon);
            //取整
            tx = parseInt(pixel.x);
            ty = parseInt(pixel.y);
            //获取marker相对鼠标的位置
            x1 = clickMarker ? e.clientX : event.clientX;
            y1 = clickMarker ? e.clientY : event.clientY;
        });
    }
}
//设置设备类型或设备状态下拉框选择
function setSelectValue(id, value) {
    var html = '';
    if (id == 'channel') {
        if (value == "枪机") {
            html = '<select id="channel" class="easyui-combobox"> <option value="枪机" selected="selected">枪机</option><option value="球机">球机</option><option value="半球">半球</option></select>';
        } else if (value == "球机") {
            html = '<select id="channel"> <option value="枪机">枪机</option><option value="球机" selected="selected">球机</option><option value="半球">半球</option></select>';
        } else {
            html = '<select id="channel"> <option value="枪机">枪机</option><option value="球机">球机</option><option value="半球" selected="selected">半球</option></select>';
        }
    } else {
        if (value == "0") {
            html = '<select id="sbstatus"> <option value="0" selected="selected">在线</option><option value="1">不在线</option></select>';
        } else {
            html = '<select id="sbstatus"> <option value="0">在线</option><option value="1" selected="selected">不在线</option></select>';
        }
    }
    return html;
}

//关闭窗口
function closeInfoWin() {
    if (infowin) {
        try {
            infowin.hide();
            infowin.destroy();
            //menu.style.visibility="hidden";
            menu.css("visibility", "hidden");
        }
        catch (e) { }
    }
}
//根据id获取指定下拉框的值(公共方法)
function GetSelectValue(id) {
    var index = document.getElementById(id).selectedIndex;
    var value = document.getElementById(id).options[index].value;
    return value;
}
//marker移动方法
function movemouse(e) {
    //鼠标的实时位置
    if (isdrag) {
        if (mousetype == 1) {
            closeInfoWin();
            e = e || event;
            var x2, y2, marker, tempSm_capital;
            if (markerlayer.markers.length == 1) {
                marker = markerlayer.markers[0];
                tempSm_capital = marker.sm_capital;
            }
            //获取鼠标的实时位置
            x2 = marker ? tx + e.clientX - x1 : tx + event.clientX - x1;
            y2 = marker ? ty + e.clientY - y1 : ty + event.clientY - y1;
            //转为屏幕坐标
            var pix = new SuperMap.Pixel(x2, y2);
            //屏幕坐标转为经纬度坐标
            var lon1 = map.getLonLatFromPixel(pix);
            //将此前的marker坐标清理
            devices = [];
            clusterLayer.removeAllFeatures();
            markerlayer.clearMarkers();
            //var offset = new SuperMap.Pixel(x2,y2);
            var size = new SuperMap.Size(44, 33);
            var offset = new SuperMap.Pixel(-(size.w / 2), -size.h);
            var icon = new SuperMap.Icon('../js/map/theme/images/marker.png', size, offset);
            marker = new SuperMap.Marker(lon1, icon);
            marker.sm_capital = tempSm_capital;
            marker.events.on({ "click": mouseClickHandler, "touchstart": mouseClickHandler, "scope": marker });
            //初始化标记覆盖物类
            //注册事件
            marker.events.register("mousedown", marker, function (e) {
                isdrag = true;
                mousetype = 1;
                var lon = marker.lonlat;
                var pixel = map.getPixelFromLonLat(lon);
                tx = parseInt(pixel.x);
                ty = parseInt(pixel.y);
                x1 = marker ? e.clientX : event.clientX;
                y1 = marker ? e.clientY : event.clientY;
            });
            markerlayer.addMarker(marker);
            devices.push(marker);
            //parent.window.setXY(lon1.lon, lon1.lat);
        } else {
            closeInfoWin();
            e = e || event;
            var x2, y2, marker, tempSm_capital;
            if (markerlayer.markers.length == 1) {
                marker = markerlayer.markers[0];
                tempSm_capital = marker.sm_capital;
            } else {
                //marker = clickMarker.marker;
                marker = clickMarker;
                //tempSm_capital = marker.sm_capital;
            }
            //获取鼠标的实时位置
            x2 = marker ? tx + e.clientX - x1 : tx + event.clientX - x1;
            y2 = marker ? ty + e.clientY - y1 : ty + event.clientY - y1;
            //转为屏幕坐标
            var pix = new SuperMap.Pixel(x2, y2);
            //屏幕坐标转为经纬度坐标
            var lon1 = map.getLonLatFromPixel(pix);
            //将此前的marker坐标清理
            clusterLayer.removeAllFeatures();
            markerlayer.clearMarkers();
            //var offset = new SuperMap.Pixel(x2,y2);
            var size = new SuperMap.Size(32, 32);
            var offset = new SuperMap.Pixel(-(size.w / 2), -size.h);
            var icon = new SuperMap.Icon('../js/map/theme/images/cluster1.png', size, offset);
            marker = new SuperMap.Marker(lon1, icon);
            marker.sm_capital = tempSm_capital;
            //初始化标记覆盖物类
            //注册事件
            marker.events.register("mousedown", marker, function (e) {
                isdrag = true;
                mousetype = 2;
                var lon = marker.lonlat;
                var pixel = map.getPixelFromLonLat(lon);
                tx = parseInt(pixel.x);
                ty = parseInt(pixel.y);
                x1 = marker ? e.clientX : event.clientX;
                y1 = marker ? e.clientY : event.clientY;
            });
            markerlayer.addMarker(marker);
            //clickMarker.marker=marker;
            clickMarker = marker;
            clickMarker.lonlat = marker.lonlat;
            EditMarker();
        }
    }
}
document.onmousemove = movemouse;
document.onmouseup = function () {

    isdrag = false;
}
$("#map").on("click", function () {
    //	        if (!$("#deviceName")[0]) {
    //	            console.log(1);
    //	            $("#txtPlace").focus();
    //	        }
})
//改变移动状态
function updateDrag(type) {
    if (type == 1) {
        $('#isdrag').val('false');
    } else {
        $('#isdrag').val('true');
    }
}
/************************************添加设备************************************/
//添加事件
function addFeatureCompleted(x, y) {
    var feau = {};
    var deviceName = document.getElementById("deviceName").value;
    var cameraID = $("#cameraName").val();
    var deviceType = $("#deviceType").combobox("getValue");
    if (deviceName == "" || cameraID == "") {
        layer.msg("请填写完必填信息！");
        return;
    }
    $.ajax({
        type: "post",
        url: baseUrl + 'SaveDevice',
        async: true,
        data: { DeviceName: deviceName, CameraID: cameraID, DeviceType: deviceType, Longitude: x, Latitude: y },
        success: function (result) {
            var lresult = $.parseJSON(result);
            if (lresult.code == 1) {
                layer.msg("添加成功");
                layer.closeAll();
                markerlayer.clearMarkers();
                var geometry = new SuperMap.Geometry.Point(x, y);
                var feaus = new Array();
                feau = {
                    fieldNames: ["ID", "DeviceName", "CameraID", "DeviceType", "Longitude", "Latitude", "RegionName", "Company", "bak1", "bak2"],
                    fieldValues: [lresult.msg, deviceName, cameraID, deviceType, x, y, "", "", "", ""],
                    geometry: geometry
                };
                feaus.push(feau)
                SetParasql(feaus);
                setTimeout(function () { layer.msg("添加成功！"); }, 500);
                //showAlldevice("");
            } else {
                layer.msg(lresult.msg);
            }
            closeInfoWin();
        },
        error: function (XMLHttpRequest, textStatuss, errorThrown) {
            document.write(XMLHttpRequest.responseText);
        },
        beforeSend: function (xmlHttp) {
            xmlHttp.setRequestHeader("If-Modified-Since", "0");
            xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        }
    });
}
//交互Iserver
function SetParasql(obj, bool) {
    var editFeatureParemeter, editFeatureService;
    var features = obj;
    editFeatureParemeter = new SuperMap.REST.EditFeaturesParameters({
        features: obj,
        editType: SuperMap.REST.EditType.ADD,
        returnContent: true,
        isUseBatch: true
    });
    editFeatureService = new SuperMap.REST.EditFeaturesService(url2, {
        eventListeners: {
            "processCompleted": function (e) {
                addFeaturesProcessCompleted(e, bool);
            },
            "processFailed": processFailed
        }
    });
    editFeatureService.processAsync(editFeatureParemeter);

}
//添加地物成功
function addFeaturesProcessCompleted(editFeaturesEventArgs, bool) {
    drawBounds.deactivate();
    var addResultIds = editFeaturesEventArgs.result.IDs,
            resourceInfo = editFeaturesEventArgs.result.resourceInfo;
    if (addResultIds === null && resourceInfo === null) return;

    if ((addResultIds && addResultIds.length > 0) || (resourceInfo && resourceInfo.succeed)) {
        console.log("新增地物成功");
    } else {
        console.log("新增地物失败");
    }
    if (bool) {
        layer.closeAll();
        layer.msg("同步成功");
    }
}
function processFailed(e) {
    layer.msg(e.error.errorMsg);
    layer.closeAll('loading');
}
/************************************修改设备************************************/
//根据设备类型查询数据
function getFeatureBySQL(id) {
    var getFeatureParam, getFeatureBySQLParams, getFeatureBySQLService;
    getFeatureParam = new SuperMap.REST.FilterParameter({
        name: SuppiNewDataName,
        attributeFilter: "SMID > 0 and ID='" + id + "'"
    });
    getFeatureBySQLParams = new SuperMap.REST.GetFeaturesBySQLParameters({
        queryParameter: getFeatureParam,
        datasetNames: [SuppiNewData],
        maxFeatures: 5000,
        fromIndex: 0,
        toIndex: 5000
    });
    //debugger;
    getFeatureBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url3, {
        eventListeners: {
            "processCompleted": function (e) {
                processFeatureSQLCompleted(e);
            },
            "processFailed": processFailed
        }
    });
    getFeatureBySQLService.processAsync(getFeatureBySQLParams);
}

function processFeatureSQLCompleted(getFeaturesEventArgs) {
    var i, len, features, fields, result = getFeaturesEventArgs.result;
    if (result && result.features) {
        features = result.features;
        if (features.length > 0) {
            clickfeatrue = features[0];
        }
    }
}
function editFeatureCompleted(x, y) {
    var feau;
    var ID = document.getElementById("ID").value;
    var DeviceName = document.getElementById("DeviceName").value;
    var channel = $("#channel").combobox("getValue");
    var CameraID = $("#CameraID").val();
    if (DeviceName == "" && CameraID == "" && channel == "") {
        layer.msg("请填写完整的参数");
        return;
    }
    $.ajax({
        type: "post",
        url: baseUrl + 'SaveDevice',
        async: false,
        data: { ID: ID, DeviceName: DeviceName, CameraID: CameraID, DeviceType: channel, Longitude: x, Latitude: y, bak: "" },
        success: function (result) {
            var lresult = $.parseJSON(result);
            if (lresult.code == 1) {
                layer.msg("添加成功");
                layer.closeAll();
                markerlayer.clearMarkers();
                var geometry = new SuperMap.Geometry.Point(x, y);
                feau = {
                    fieldNames: ["ID", "DeviceName", "CameraID", "DeviceType", "Longitude", "Latitude", "RegionName", "Company", "bak1", "bak2"],
                    fieldValues: [ID, DeviceName, CameraID, channel, x, y, "", "", "", ""],
                    geometry: geometry
                };
                console.log(clickfeatrue.fid);
                if (clickfeatrue != null) {
                    feau.geometry.id = clickfeatrue.fid;
                }
                editFeature(feau);
            } else {
                layer.msg(lresult.msg);
            }
            closeInfoWin();
        },
        error: function (XMLHttpRequest, textStatuss, errorThrown) {
            document.write(XMLHttpRequest.responseText);
        },
        beforeSend: function (xmlHttp) {
            xmlHttp.setRequestHeader("If-Modified-Since", "0");
            xmlHttp.setRequestHeader("Cache-Control", "no-cache");
        }
    });

}
//编辑事件
function editFeature(obj) {
    var editFeatureParemeter, editFeatureService;
    var features = obj;
    editFeatureParemeter = new SuperMap.REST.EditFeaturesParameters({
        features: [features],
        editType: SuperMap.REST.EditType.UPDATE,
        returnContent: true
    });
    editFeatureService = new SuperMap.REST.EditFeaturesService(url2, {
        eventListeners: {
            "processCompleted": editFeaturesProcessCompleted,
            "processFailed": processFailed
        }
    });
    editFeatureService.processAsync(editFeatureParemeter);
}
//编辑结果
function editFeaturesProcessCompleted(editFeatureEventArgs) {
    modifyFeature.deactivate();
    if (editFeatureEventArgs.result.resourceInfo.succeed) {
        layer.msg("保存成功");
        clearAllFeatures();
        //showAlldevice("");;
    } else {
        layer.msg("保存失败");
    }
    clickfeatrue = null;
    clickfield = null;
    clickMarker = null;
    clickType = null;
    add = 0;
}
/************************************结束************************************/
/************************************删除设备************************************/
//删除方法
function deleteSelectedFeature(id) {
    if (window.confirm("确认删除？")) {
        //clearAllDeactivate();
        $.ajax({
            type: "post",
            url: baseUrl + 'DeleteDevice',
            async: false,
            data: { ID: id },
            success: function (result) {
                var lresult = $.parseJSON(result);
                if (lresult.code == 1) {
                    layer.closeAll();
                    markerlayer.clearMarkers();
                    var editFeatureParameter, editFeatureService;
                    var ids = new Array();
                    ids.push(clickfeatrue.fid);
                    clearAllFeatures();
                    editFeatureParameter = new SuperMap.REST.EditFeaturesParameters({
                        IDs: ids,
                        editType: SuperMap.REST.EditType.DELETE
                    });
                    editFeatureService = new SuperMap.REST.EditFeaturesService(url2, {
                        eventListeners: {
                            "processCompleted": deleteFeaturesProcessCompleted,
                            "processFailed": processFailed
                        }
                    });
                    editFeatureService.processAsync(editFeatureParameter);
                } else {
                    layer.msg(lresult.msg);
                }
                closeInfoWin();
            },
            error: function (XMLHttpRequest, textStatuss, errorThrown) {
                document.write(XMLHttpRequest.responseText);
            },
            beforeSend: function (xmlHttp) {
                xmlHttp.setRequestHeader("If-Modified-Since", "0");
                xmlHttp.setRequestHeader("Cache-Control", "no-cache");
            }
        });

    }
}
//删除结果
function deleteFeaturesProcessCompleted(editFeaturesEventArgs) {
    if (editFeaturesEventArgs.result.resourceInfo.succeed) {
        layer.msg("删除成功");
        //重新加载图层
        //clearAllFeatures();
    } else {
        layer.msg("删除失败");
    }
    //del = 0;
}
/*****************************************圆形查询********************************************/
function creatMarker(x, y) {
    //	var markersLayer = new SuperMap.Layer.Markers( "Marker" );
    //	map.addLayer(markersLayer);
    clearAllFeatures();
    var size = new SuperMap.Size(37, 33);
    var offset = new SuperMap.Pixel(-(size.w / 2), -size.h + 2);
    var icon = new SuperMap.Icon('../js/map/theme/images/marker-gold.png', size, offset);
    //初始化标记覆盖物类
    var marker = new SuperMap.Marker(new SuperMap.LonLat(x, y), icon);
    marker.sm_capital = cd;
    centerlayer.addMarker(marker);
    devices.push(marker);
    dis = 0.05;
    CircularX = x;
    CircularY = y;
    centerPoint = new SuperMap.Geometry.Point(x, y);
    queryByDistanceStart(x, y);
}

function queryByDistanceStart(x, y) {
    dis = 0.05; //设置第一次查询的默认值
    drawBufferCompleted(dis); //初始半径距离查询
    setDrag(x, y); //拖动选择半径
}
//圆形查询
function queryByCircular(queryDis) {
    //地图定位至当前查询范围
    var polygon = SuperMap.Geometry.Polygon.createRegularPolygon(centerPoint, queryDis, 50, 270);
    var bound = polygon.getBounds();
    map.zoomToExtent(polygon.getBounds());
    markerlayer.clearMarkers();
    var darasetName = [SuppiNewData];
    var GetFeaturesByBoundsParameters, getFeaturesByGeometryService;
    GetFeaturesByBoundsParameters = new SuperMap.REST.GetFeaturesByBoundsParameters({
        datasetNames: darasetName,
        spatialQueryMode: SuperMap.REST.SpatialQueryMode.INTERSECT,
        bounds: bound,
        maxFeatures: 5000,
        fromIndex: 0,
        toIndex: 5000

    });
    getFeaturesByGeometryService = new SuperMap.REST.GetFeaturesByBoundsService(url3, {
        eventListeners: {
            "processCompleted": processBoundCompleted,
            "processFailed": processFailed
        }
    });
    getFeaturesByGeometryService.processAsync(GetFeaturesByBoundsParameters);
}

function processFailed(e) {
    layer.msg(e.error.errorMsg);
}

function setDrag(x, y) {
    vectorLayer.removeAllFeatures();

    //显示初始圆
    var polygon = SuperMap.Geometry.Polygon.createRegularPolygon(centerPoint, dis, 50, 270);
    vectorLayer.addFeatures(new SuperMap.Feature.Vector(polygon, circleStyle));

    var lon = parseFloat(x) + parseFloat(dis);
    //显示初始拖动按钮
    var dragButtonLonlat = new SuperMap.LonLat(lon, y);
    var pixe = map.getPixelFromLonLat(dragButtonLonlat);
    $("#dragButton").css({
        top: (pixe.y - 8) + "px",
        left: (pixe.x - 13) + "px"
    });
    $("#distance").val(dis + "米");
    $("#dragButton").show();

    $('#dragButton').mousedown(
		function (event) {
		    //鼠标按下时，获取圆心的屏幕坐标
		    var centerPixelX = event.pageX - map.getPixelFromLonLat(new SuperMap.LonLat(x, y)).x;
		    var centerPixelY = map.getPixelFromLonLat(new SuperMap.LonLat(x, y)).y;

		    $('#map').mousemove(
				function (event) {
				    //取消浏览器的默认拖动事件
				    event.preventDefault();
				    event.stopPropagation();
				    var eventPixel = new SuperMap.Pixel(event.pageX, centerPixelY); //拖动时的鼠标屏幕坐标
				    dis = map.getLonLatFromPixel(eventPixel).lon - CircularX; //拖动时的半径
				    var obj = $('#dragButton');
				    //控制拖动按钮向左不能超过圆心
				    if (event.pageX > map.getPixelFromLonLat(new SuperMap.LonLat(CircularX, CircularY)).x) {
				        obj.css({
				            'left': event.pageX - 13,
				            'top': centerPixelY - 8
				        }); //拖动按钮的位置随鼠标移动改变
				        $("#distance").val(dis.toFixed(0) + "米"); //显示半径文本框中的半径值
				        //实时画圆
				        var polygon = SuperMap.Geometry.Polygon.createRegularPolygon(centerPoint, dis, 50, 270);
				        vectorLayer.removeAllFeatures();
				        vectorLayer.addFeatures(new SuperMap.Feature.Vector(polygon, circleStyle));
				    }
				}
			).mouseup(
				function (event) {
				    //移除鼠标拖动方法
				    $('#map').unbind("mousemove");
				    //移除鼠标抬起方法
				    $('#map').unbind("mouseup");
				    //根据当前半径进行距离查询
				    drawBufferCompleted(dis);

				}
			);
		}
	);
}

function move() {
    //在拖动地图的过程中，使拖动按钮随着地图移动
    var lon = parseFloat(CircularX) + parseFloat(dis);
    if ($('#dragButton').is(":visible")) {
        var pixcel = map.getPixelFromLonLat(new SuperMap.LonLat(lon, CircularY));
        $('#dragButton').css({
            'left': pixcel.x - 13,
            'top': pixcel.y - 8
        });
    }
}
//缓冲查询
function drawBufferCompleted(queryDis) {
    var polygon = SuperMap.Geometry.Polygon.createRegularPolygon(centerPoint, queryDis, 50, 270);
    map.zoomToExtent(polygon.getBounds());
    markerlayer.clearMarkers();
    var darasetName = [SuppiNewData];
    var getFeatureParameter, getFeatureService;
    getFeatureParameter = new SuperMap.REST.GetFeaturesByBufferParameters({
        bufferDistance: queryDis,
        datasetNames: darasetName,
        returnContent: true,
        geometry: centerPoint,
        maxFeatures: 5000,
        fromIndex: 0,
        toIndex: 5000

    });
    getFeatureService = new SuperMap.REST.GetFeaturesByBufferService(url3, {
        eventListeners: {
            "processCompleted": processBoundCompleted,
            "processFailed": processFailed
        }
    });
    getFeatureService.processAsync(getFeatureParameter);
}
//同步数据
function synchronization() {
    layer.confirm('确定同步数据?', { icon: 3, title: '提示' }, function (index) {
        //do something

        layer.close(index);
        layer.load(0, { //icon支持传入0-2
            shade: [0.5, 'gray'], //0.5透明度的灰色背景
            content: '同步中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'color': '#fff',
                    'font-size': '24px',
                    'padding-top': '39px',
                    'width': '95px'
                });
            }
        });
        //deleteFeatureCommon(null, true);
        //deleteAllFeatrue();
        setTimeout(function () {
            setFeature(true);
        }, 1000);
        AllFeatureDelete();
    });
}
function confirmDelete() {
    layer.confirm('确定删除数据数集?', { icon: 3, title: '提示' }, function (index) {
        //do something

        layer.close(index);

        AllFeatureDelete();
        setTimeout(function () {
            layer.msg("删除成功");
        }, 1000);
    });
}
function AllFeatureDelete() {
    try {
        var commit = getcommit();
        commit.open("POST", encodeURI(url5), false, "", "");
        //commit.setRequestHeader("Access-Control-Allow-Headers", "*");
        commit.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        //commit.setRequestHeader("Access-Control-Allow-Origin", "*");
        commit.send(toJSON({ "attributeFilter": "SMID > 0" }));
        console.log(commit.responseText);
        var response = json_parse(commit.responseText, null);
        console.log(commit.responseText);
    } catch (e) {
        console.log(e);
    }

}
//查出数据所有数据并删除
function deleteAllFeatrue() {
    var getFeatureParam, getFeatureBySQLParams, getFeatureBySQLService;
    getFeatureParam = new SuperMap.REST.FilterParameter({
        name: SuppiNewDataName,
        attributeFilter: " SMID > 0"
    });
    getFeatureBySQLParams = new SuperMap.REST.GetFeaturesBySQLParameters({
        queryParameter: getFeatureParam,
        datasetNames: [SuppiNewData],
        maxFeatures: 5000,
        fromIndex: 0,
        toIndex: 5000
    });
    //debugger;
    getFeatureBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url3, {
        eventListeners: {
            "processCompleted": function (e) {
                delFeatureSQL(e);
            },
            "processFailed": processFailed
        }
    });
    getFeatureBySQLService.processAsync(getFeatureBySQLParams);
}
function delFeatureSQL(getFeaturesEventArgs) {
    try {
        var i, len, features, fields, result = getFeaturesEventArgs.result;
        if (result && result.features) {
            features = result.features;
            if (features.length > 0) {
                for (var i = 0; i < features.length; i++) {
                    var ids = new Array();
                    ids.push(features[i].fid);

                    if (i == features.length - 1) {
                        deleteFeatureCommon(ids, true); //setFeature(true);
                    } else {
                        deleteFeatureCommon(ids);
                    }
                }
            } else {
                setFeature(true);
            }
            //            setTimeout(function () {
            //                if (ids.length / 100 > 0) {
            //                    var num = parseInt(ids.length / 100);

            //                    console.log(parseInt(ids.length / 100) + "," + ids.length % 100);
            //                    if (num > 0) {
            //                        for (var j = 0; j < num; j++) {
            //                            deleteFeatureCommon(ids.slice(j * 100, (j * 100) + 99));
            //                            if (j == num - 1) {
            //                                deleteFeatureCommon(ids.slice(j * 100, (j * 100) + (ids.length % 100)));
            //                            }
            //                        }
            //                    } else {
            //                        deleteFeatureCommon(ids);
            //                    }
            //                } else {
            //                    
            //                }
            //            }, 200);
        }
    } catch (e) {
        layer.closeAll();
        layer.msg(e);
    }
}
function deleteFeatureCommon(obj, bool) {
    var editFeatureParameter1, editFeatureService1;
    editFeatureParameter1 = new SuperMap.REST.EditFeaturesParameters({
        IDs: obj,
        // attributeFilter: " SMID > 0",
        editType: SuperMap.REST.EditType.DELETE
    });
    editFeatureService1 = new SuperMap.REST.EditFeaturesService(url2, {
        eventListeners: {
            "processCompleted": function (e) {
                delFeaturesProcessCompleted(e, bool);
            },
            "processFailed": processFailed
        }
        // ,isInTheSameDomain:true
    });
    editFeatureService1.processAsync(editFeatureParameter1);

}
//删除结果
function delFeaturesProcessCompleted(editFeaturesEventArgs, bool) {
    if (bool) {
        setFeature(true);
    }
    if (editFeaturesEventArgs.result.resourceInfo.succeed) {
        console.log("删除成功");

    } else {
        layer.msg("删除失败");
    }
    //del = 0;
}
function setFeature(bool) {
    try {
        if (bool) {
            $.ajax({
                type: "get",
                url: baseUrl + 'SetDeviceList',
                async: false,
                success: function (Request) {
                    var lRequest = $.parseJSON(Request);
                    if (lRequest.code == 1) {
                        $.ajax({
                            type: "get",
                            url: baseUrl + 'GetDeviceListByWhere',
                            async: true,
                            success: function (result) {
                                var lresult = $.parseJSON(result);
                                if (lresult.code == 1) {
                                    var data = eval(lresult.data);
                                    var feaus = new Array();
                                    for (var i = 0; i < data.length; i++) {

                                        var geometry = new SuperMap.Geometry.Point(data[i].Longitude, data[i].Latitude);
                                        var feau = {
                                            fieldNames: ["ID", "DeviceName", "CameraID", "DeviceType", "Longitude", "Latitude", "RegionName", "Company", "bak1", "bak2"],
                                            fieldValues: [data[i].ID, data[i].DeviceName, data[i].CameraID, data[i].DeviceType, data[i].Longitude, data[i].Latitude, "", "", data[i].bak, ""],
                                            geometry: geometry
                                        };
                                        feaus.push(feau);
                                    }
                                    if (feaus.length > 1000) {
                                        var len = parseInt(feaus.length / 1000);
                                        timeSet(len, 0, feaus, false);
                                    } else {
                                        setTimeout(function () { SetParasql(feaus, true); }, 100);
                                    }

                                } else {
                                    layer.msg(lresult.msg);
                                    layer.closeAll();
                                }
                            },
                            error: function (XMLHttpRequest, textStatuss, errorThrown) {
                                document.write(XMLHttpRequest.responseText);
                            },
                            beforeSend: function (xmlHttp) {
                                xmlHttp.setRequestHeader("If-Modified-Since", "0");
                                xmlHttp.setRequestHeader("Cache-Control", "no-cache");
                            }
                        });
                    } else {
                        layer.msg(lRequest.msg);
                        layer.closeAll();
                    }
                },
                error: function (XMLHttpRequest, textStatuss, errorThrown) {
                    document.write(XMLHttpRequest.responseText);
                },
                beforeSend: function (xmlHttp) {
                    xmlHttp.setRequestHeader("If-Modified-Since", "0");
                    xmlHttp.setRequestHeader("Cache-Control", "no-cache");
                }
            });

        }
    } catch (e) {
        layer.closeAll();
        layer.msg(e);
    }
}
function timeSet(len, i, data, bool) {
    var time = 0;
    if (i < len + 1) {
        bool = false;
        if (i > 0) {
            time = 700;
        }
        var fearr = data.slice(i * 1000, i * 1000 + 1000);
        if (i == len) {
            fearr = data.slice(i * 1000, i * 1000 + (data.length % 1000));
            bool = true;
            time = len * 1000;
        }
        SetParasql(fearr, bool);
        i++;
        setTimeout(function () { timeSet(len, i, data, bool); }, time);
    }
}